package com.CampaignManager.server;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.CampaignManager.shared.CalendarUtil;

//D:\curl-7.22.0-ssl-sspi-zlib-static-bin-w32>curl http://127.0.0.1:8888/cron/dailyTask

@SuppressWarnings("serial")
public class DailyTask extends HttpServlet {
	
	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
			
    	PersistenceManager pm = CampaignServiceImpl.PMF.getPersistenceManager();
    	try {
    		List<String> peopleToEmail = new ArrayList<String>();
    		
    		Query p = pm.newQuery(Player.class);
			List<Player> players = (List<Player>) p.execute();
			
			Query u = pm.newQuery(Unit.class);
			List<Unit> units = (List<Unit>) u.execute();
			
			for (Player player : players) {
				
				PlayerResource playerGold = player.getResource("Gold");
												
				for (Unit unit : units) {
					if (unit.getOwnerEmail().equalsIgnoreCase(player.getEmail())) {
						
						Long weeklyCost = unit.getPoints() * 5;
						
						if (CalendarUtil.getDaysBetween(unit.getLastPaid(),  new Date()) >= 7) {
							if (weeklyCost > playerGold.getAmount()) {
								playerGold.setAmount(0L);
								unit.setPoints(unit.getPoints()-1);
								if (!peopleToEmail.contains(player.getEmail())) {
									peopleToEmail.add(player.getEmail());
								}
							} else {
								playerGold.setAmount(playerGold.getAmount()-weeklyCost);
								unit.setLastPaid(new Date());
							}
						}						
					}
				}
			
			}
			
			if (peopleToEmail.size() > 0) {
				Properties props = new Properties();         
				Session session = Session.getDefaultInstance(props, null);
				String msgBody = "<p>Your troops are leaving because of they're not getting paid! Earn enough gold to pay your wages or you'll loose your army. <a href='http://warmachinemanager.appspot.com/'>link</a>.<p>";
				try {
					Message msg = new MimeMessage(session);
					msg.setFrom(new InternetAddress("schroe2a@gmail.com", "Warmachine Campaign Manager Admin"));
					for (String email : peopleToEmail) {
						msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
					}					
					msg.addRecipient(Message.RecipientType.TO, new InternetAddress("schroe2a@gmail.com"));
					msg.setSubject("Warning: Troops Defecting!");
					msg.setContent(msgBody, "text/html");				
					Transport.send(msg);
				} catch (AddressException e) {
					CampaignServiceImpl.LOG.log(Level.WARNING, "addMessage got AddressException trying to email daily warning");
				} catch (MessagingException e) {
					CampaignServiceImpl.LOG.log(Level.WARNING, "addMessage got MessagingException trying to email daily warning");
				} catch (UnsupportedEncodingException e) {
					CampaignServiceImpl.LOG.log(Level.WARNING, "addMessage got UnsupportedEncodingException trying to email daily warning");
				}
			}
    	} finally {
    		pm.close();
    	}   
	}
}
